#use a dir to implement a disk queue
#the queue is used by  some write processes and a read process(can be multi threads)
import glob
import os
def cmp(a1,a2):
	'''
	idx1=a1.find('.[')
	idx2=a1.find('-',idx1)
	i1=int(a1[idx1+2:idx2])
	
	idx1=a2.find('.[')
	idx2=a2.find('-',idx1)
	i2=int(a2[idx1+2:idx2])
	'''
	if a1<a2:return -1
	if a1==a2:return 0
	return 1
def open_done_file(dir,type,doneFile='done.txt'):
	f=open(os.path.join(dir,doneFile),type)
	return f
def one_file_done(dir,fname,doneFile='done.txt'):
	f=open_done_file(dir,'ab',doneFile)
	f.write(os.path.basename(fname)+'\n')
	f.close()
def files_done(dir,fnames,doneFile='done.txt'):
	f=open_done_file(dir,'ab',doneFile)
	for fname in fnames:
		f.write(os.path.basename(fname)+'\n')
	f.close()
def retr_undone_files(dir,ext,doneFile='done.txt'):
	files=glob.glob(os.path.join(dir,'*.'+ext))
	files.sort(cmp)
	try:
		fDone=open_done_file(dir,'rb',doneFile)
	except:
		pass
	else:
		for line in fDone.xreadlines():
			basename=line.strip()
			if not basename:
				continue
			if basename[0]=='#':
				continue
			try:
				files.remove(os.path.join(dir,basename))
			except:
				pass
		fDone.close()	
		
	try:
		files.remove(os.path.join(dir,'done.txt'))	
	except:	
		pass
	return files
